// 第1题：字符串采用定长顺序串存储结构。编程实现串的以下串的基本操作，并测试。
// 插入:insert()、替换:strreplace()、取子串:substr()、定位index()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 255
typedef char str[MAXSIZE+1];
void insert(str& s, int pos, char e) {
    int curlen = s[0];
    if (curlen >= MAXSIZE)
        exit(-2);
    if (pos > curlen + 1)
        exit(-1);
    for (int i = curlen; i >= pos; --i) {
        s[i+1] = s[i];
    }
    s[pos] = e;
    ++s[0];
}
void strreplace(str& s, int pos, str sub) {
    int newlen = sub[0];
    if (pos - 1 + newlen > MAXSIZE)
        exit(-2);
    for (int i = 1; i <= newlen; ++i) {
        s[pos+i-1] = sub[i];
    }
}
void substr(str& s, int pos, int len, str& sub) {
    if (len > s[0])
        exit(-1);
    sub[0] = len;
    for (int i = 1; i <= len; ++i) {
        sub[i] = s[pos+i-1];
    }
}
int index(str s, char e) {
    int curlen = s[0];
    for (int i = 1; i <= curlen; ++i) {
        if (s[i] == e) {
            return i;
        }
    }
    return -1;
}
void show(str s) {
    int curlen = s[0];
    for (int i = 1; i <= curlen; ++i) {
        printf("%c", s[i]);
    }
    printf("\n");
}
int main(void) {
    str s1 = "0helloworld";
    s1[0] = strlen(s1) - 1;
    str s2 = "0lxy";
    s2[0] = strlen(s2) - 1;

    show(s1);
    insert(s1, 2, 'a');
    show(s1);
    show(s2);
    strreplace(s1, 3, s2);
    show(s1);
    substr(s1, 2, 5, s2);
    show(s2);
    int i = index(s2, 'x');
    printf("i = %d\n", i);

    return 0;
}